import Sortable from 'sortablejs'
import { Ref, watchEffect, onUnmounted } from 'vue'

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function useDrag(
  wrapper: Ref,
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  itemList: any[],
  options?: Sortable.Options
) {
  let sortable: Sortable | null = null
  const onEnd = (e: Sortable.SortableEvent) => {
    if (e.oldIndex != null && e.newIndex != null) {
      // 将相应的元素插入新的位置
      // http://www.voidcn.com/article/p-gbwviaik-qg.html
      // eslint-disable-next-line prefer-spread
      itemList.splice.apply(
        itemList,
        [e.newIndex, 0].concat(itemList.splice(e.oldIndex, 1)) as [
          start: number,
          deleteCount: number,
          ...items: unknown[]
        ]
      )
    }
  }

  watchEffect(() => {
    if (wrapper.value) {
      const element = wrapper.value.$el || wrapper.value || null
      sortable = Sortable.create(element, {
        group: 'default',
        animation: 150,
        onEnd,
        ...options,
      })
    }
  })
  onUnmounted(() => {
    sortable && sortable.destroy()
  })

  return { sortable }
}
